package com.jt.chapter06.controller;

import com.jt.chapter06.utils.ImageCode;
import com.jt.chapter06.utils.ImageCodeGenerator;
import com.jt.chapter06.common.SessionKey;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jiang tao
 * @date 2022/1/19
 * @description:
 **/
@RestController
@RequestMapping("/code")
public class ValidateController {

    @Autowired
    private ImageCodeGenerator imageCodeGenerator;

    @GetMapping("")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = imageCodeGenerator.generateImageCode();

        request.getSession().setAttribute(SessionKey.SESSION_key, imageCode);
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");

        //response.setDateHeader("Expires", 0);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
        encoder.encode(imageCode.getImage());
    }
}
